package com.runachina.java;

import android.util.Log;

import java.io.IOException;
import java.net.Socket;

/**
 * Created by lyl on 2017/7/4.
 * <p>
 * 用于发送心跳包
 *
 * 30s发送一次
 *
 * 可随便发送一个字符串，无需按照协议进行发送
 */

public class ClientSender {

    public static ClientSender clientSender;

    private Socket sender;

    /*读取runa 188协议的热表*/
    public static byte[] readmeter = {(byte) 0xfe, (byte) 0xfe, (byte) 0xfe, 0x68, 0x20,
            (byte) 0xAA, (byte) 0xAA, (byte) 0xAA, (byte) 0xAA,//表号
            (byte) 0xAA, (byte) 0xAA, (byte) 0xAA, 0x01, 0x03, (byte) 0x1F, (byte) 0x90, 0x00,
            (byte) 0x00, 0x16,
            (byte) 0x00, 0x16//存放转发协议的校验和结束
    };

    private ClientSender() {


    }

    public static ClientSender getClientSender() {
        if (clientSender == null) {
            clientSender = new ClientSender();
        }
        return clientSender;
    }

    public void send(final Socket socket) {
        try {
            // sender = new Socket("192.168.7.1", 25000);
            final byte[] sendbyte = SendDataAnalysis.ReadMeterSendByte(readmeter, "123", 5, 3);//5：表号起始位置，3：报文校验和起始位置
            //发送sendbyte[]
            Log.e("liyuelong", "send:心跳包的实现 ");
            // String sendResult = TcpSocket.wifiSendByte(sendbyte, 1);
            //发送数据到服务器的时候，要重新开启一个线程，android 7.0已经修复了这个漏洞
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Log.e("liyuelong", "wifiSendByte: 心跳包进来的");
                        Log.e("liyuelong", "进来了2" );
                        if (socket!=null){
                            if (TcpSocket.isConnecting){
                                socket.getOutputStream().write("heart".getBytes());
                                socket.getOutputStream().flush();
                                Log.e("liyuelong", "socket是否连接："+socket.isConnected());
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        } catch (Exception e) {

        }

    }
}
